<template>
  <view class="fund-detail-page">
    <image class="project-banner" :src="project.image || getDefaultImage()" mode="aspectFill" />

    <view class="project-header">
      <view class="project-name">{{ project.projectName || "加载中..." }}</view>
      <view class="project-period">
        <text class="period-label">项目周期：</text>
        <text>{{ project.startDate || "--" }} 至 {{ project.endDate || "--" }}</text>
      </view>
    </view>

    <view class="fund-progress">
      <view class="progress-header">
        <view class="raised-amount">
          <text class="amount">¥{{ formatNumber(project.raisedFund || 0) }}</text>
          <text class="label">已筹金额</text>
        </view>
        <view class="target-amount">
          <text class="amount">¥{{ formatNumber(project.targetFund || 0) }}</text>
          <text class="label">目标金额</text>
        </view>
      </view>
      <wd-progress :percentage="calculateProgress(project)" :show-text="true" :stroke-width="10" />
    </view>

    <view class="project-content">
      <view class="content-title">项目介绍</view>
      <view class="content-text">{{ project.projectIntro || "暂无项目介绍" }}</view>
    </view>

    <!-- 项目进展 -->
    <view v-if="progressList.length > 0" class="project-progress">
      <view class="content-title">项目进展</view>
      <view class="timeline">
        <view v-for="(item, index) in progressList" :key="index" class="timeline-item">
          <view class="timeline-date">{{ item.date }}</view>
          <view class="timeline-content">{{ item.content }}</view>
        </view>
      </view>
    </view>

    <!-- 捐赠记录 -->
    <view class="donate-records">
      <view class="content-title">捐赠记录</view>
      <view v-if="donateRecords.length > 0" class="record-list">
        <view v-for="(record, index) in donateRecords" :key="index" class="record-item">
          <view class="donor-avatar">
            <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png" mode="aspectFill"></image>
          </view>
          <view class="record-info">
            <view class="donor-name">{{ record.donorName }}</view>
            <view v-if="record.donationMessage" class="donate-message">
              {{ record.donationMessage }}
            </view>
            <view class="donate-time">{{ record.donationTime }}</view>
          </view>
          <view class="donate-amount">
            <text>¥{{ formatNumber(record.donationAmount) }}</text>
          </view>
        </view>
      </view>
      <view v-else-if="!donateLoading" class="empty-records">
        <text>暂无捐赠记录</text>
      </view>
      <view v-else class="loading-records">
        <text>加载中...</text>
      </view>
    </view>

    <!-- 捐赠按钮 -->
    <!-- <view class="donate-button">
      <wd-button type="primary" block @click="showDonateModal">立即捐赠</wd-button>
    </view> -->

    <!-- 捐赠弹窗 -->
    <wd-popup v-model="showModal" position="bottom">
      <view class="donate-modal">
        <view class="modal-header">
          <text class="modal-title">捐赠金额</text>
          <wd-icon name="close" @click="showModal = false" />
        </view>
        <view class="modal-content">
          <view class="amount-list">
            <view
              v-for="(amount, index) in presetAmounts"
              :key="index"
              class="amount-item"
              :class="{ active: selectedAmount === amount }"
              @click="selectedAmount = amount"
            >
              {{ amount }}元
            </view>
            <view class="amount-item custom">
              <input
                v-model="customAmount"
                type="number"
                placeholder="其他金额"
                @input="handleCustomAmount"
              />
            </view>
          </view>
          <view class="donate-message">
            <input v-model="donateMessage" type="text" placeholder="请输入捐赠留言（选填）" />
          </view>
        </view>
        <view class="modal-footer">
          <wd-button type="primary" block @click="handleDonate">确认捐赠</wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { type FundProject, getFundProjectForm } from "@/api/fund";
import { getDonationRecords, type DonationRecord } from "@/api/donation";

// 项目数据
const project = ref<FundProject>({} as FundProject);
const projectId = ref(0);

// 解析项目进展
const progressList = computed(() => {
  if (!project.value.progressArray) return [];

  try {
    const progress = JSON.parse(project.value.progressArray);
    return progress.sort((a: any, b: any) => {
      // 按日期降序排序
      return new Date(b.date).getTime() - new Date(a.date).getTime();
    });
  } catch (e) {
    console.error("解析项目进度数据失败", e);
    return [];
  }
});

// 捐赠记录
const donateRecords = ref<DonationRecord[]>([]);
const donateLoading = ref(false);
const donateTotal = ref(0);

// 捐赠弹窗相关
const showModal = ref(false);
const selectedAmount = ref(0);
const customAmount = ref("");
const donateMessage = ref("");
const presetAmounts = [100, 500, 1000, 2000, 5000];

// 获取默认图片
const getDefaultImage = () => {
  if (project.value.projectType === "修谱") return "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/6dbd9f9fdab44ca4a6409ad787126bb3.png";
  if (project.value.projectType === "修墓") return "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/9780ab19c86840c086e361eb576940b1.png";
  if (project.value.projectType === "修祠") return "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/8de8503736f244718c1dd3c2abd042b3.png";
  return "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/6dbd9f9fdab44ca4a6409ad787126bb3.png";
};

// 格式化数字
const formatNumber = (num: number) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 计算进度
const calculateProgress = (project: FundProject) => {
  if (!project.targetFund || project.targetFund === 0) return 0;
  const progress = (project.raisedFund / project.targetFund) * 100;
  return Math.min(100, Math.max(0, Math.round(progress)));
};

// 获取项目详情
const getProjectDetail = (id: number) => {
  getFundProjectForm(id)
    .then((res) => {
      if (res) {
        project.value = res;
      }
    })
    .catch((err) => {
      console.error("获取项目详情失败", err);
      uni.showToast({
        title: "获取项目详情失败",
        icon: "none",
      });
    });
};

// 获取捐赠记录
const getDonateRecords = (id: number) => {
  if (!id) return;

  donateLoading.value = true;
  getDonationRecords({
    projectId: id,
    pageNum: 1,
    pageSize: 10,
  })
    .then((res) => {
      if (res && res.list) {
        donateRecords.value = res.list;
        donateTotal.value = res.total;
      }
    })
    .finally(() => {
      donateLoading.value = false;
    });
};

// 显示捐赠弹窗
const showDonateModal = () => {
  showModal.value = true;
};

// 处理自定义金额输入
const handleCustomAmount = (e: any) => {
  const value = e.detail.value;
  if (value) {
    selectedAmount.value = 0;
  }
};

// 处理捐赠
const handleDonate = () => {
  const amount = selectedAmount.value || Number(customAmount.value);
  if (!amount) {
    uni.showToast({
      title: "请选择或输入捐赠金额",
      icon: "none",
    });
    return;
  }

  // TODO: 调用支付接口
  uni.showLoading({
    title: "处理中...",
  });

  setTimeout(() => {
    uni.hideLoading();
    showModal.value = false;
    uni.showToast({
      title: "捐赠成功",
      icon: "success",
    });
  }, 1500);
};

// 初始化
onMounted(() => {
  const pages = getCurrentPages();
  const page = pages[pages.length - 1] as any;

  // 获取项目ID
  if (page.options && page.options.id) {
    projectId.value = Number(page.options.id);
    getProjectDetail(projectId.value);
    // 加载捐赠记录
    getDonateRecords(projectId.value);
  }
});
</script>

<style lang="scss">
.fund-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.project-banner {
  width: 100%;
  height: 400rpx;
}

.project-header {
  background-color: #fff;
  padding: 30rpx;

  .project-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 15rpx;
  }

  .project-period {
    font-size: 26rpx;
    color: #666;

    .period-label {
      color: #999;
    }
  }
}

.fund-progress {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;

  .progress-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;

    .raised-amount,
    .target-amount {
      text-align: center;

      .amount {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #1989fa;
        margin-bottom: 10rpx;
      }

      .label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.project-content {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;

  .content-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .content-text {
    font-size: 28rpx;
    color: #666;
    line-height: 1.8;
    white-space: pre-wrap;
  }
}

.project-progress {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;

  .content-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .timeline {
    .timeline-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .timeline-date {
        width: 120rpx;
        font-size: 28rpx;
        color: #999;
      }

      .timeline-content {
        flex: 1;
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

.donate-records {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;

  .content-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .record-list {
    .record-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .donor-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 20rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .record-info {
        flex: 1;

        .donor-name {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
        }

        .donate-message {
          font-size: 26rpx;
          color: #666;
          margin-top: 10rpx;
        }

        .donate-time {
          font-size: 24rpx;
          color: #999;
          margin-top: 6rpx;
        }
      }

      .donate-amount {
        font-size: 30rpx;
        font-weight: bold;
        color: #ff6b00;
      }
    }
  }

  .empty-records {
    padding: 50rpx 0;
    text-align: center;
    color: #999;
    font-size: 28rpx;
  }
}

.donate-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.donate-modal {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .modal-content {
    .amount-list {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -10rpx;
      margin-bottom: 30rpx;

      .amount-item {
        width: calc(33.33% - 20rpx);
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        margin: 10rpx;
        font-size: 28rpx;
        color: #333;

        &.active {
          background-color: #1989fa;
          color: #fff;
        }

        &.custom {
          input {
            width: 100%;
            height: 100%;
            text-align: center;
            font-size: 28rpx;
          }
        }
      }
    }

    .donate-message {
      input {
        width: 100%;
        height: 80rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
      }
    }
  }

  .modal-footer {
    margin-top: 30rpx;
  }
}
</style>
